import urllib2
import struct, json
import ssl
import socket
import binascii
import CONSTANTS
import traceback
import time
import redis
from apns import APNs, Payload
from threading import Thread
import database
import struct
redis_conn = redis.Redis()

apns_feedback_add = ('feedback.push.apple.com', 2196)


def connectedAPNS(app_id):
    print 'connecting to apple feedback'
    while True:
        try:
            s = socket.socket()
            if app_id == CONSTANTS.APP.IONLINE:
                v_tmp = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv3, certfile='ionline.pem', keyfile='ionline.key')
            elif app_id == CONSTANTS.APP.ICO:
                v_tmp = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv3, certfile='ionline.pem', keyfile='ionline.key')
            v_tmp.connect(apns_feedback_add)
            print 'connected to apple feedback'
            break
        except:
            traceback.print_exc()
            time.sleep(1)
    return v_tmp


def save(msg):
    if len(msg) < 38:
        return
    f = open('feedback', 'a')
    f.write(str(struct.unpack_from('!lh32s', msg)) + '\n')
    f.close()
    print str(struct.unpack_from('!lh32s', msg))

v_ssl_sock = connectedAPNS(CONSTANTS.APP.IONLINE)
v_read = 0
while True:
    v_msg = ''
    try:
        while len(v_msg) < 38:
            v_data = v_ssl_sock.recv(38 - len(v_msg))
            v_msg = v_msg + v_data
            if not v_data:
                time.sleep(5)
    except:
        v_ssl_sock = connectedAPNS(CONSTANTS.APP.IONLINE)
        continue
    print v_msg
    save(v_msg)